package cn.com.inossem.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.db.DatabaseHelper;
import cn.com.inossem.model.RetrieveInfoBean;
import cn.com.inossem.model.RetrieveInfoModel;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.Utils;

import com.foxykeep.datadroid.requestmanager.Request;
import com.google.gson.Gson;

/**
 * 
 * 城市
 * 
 * <p>
 * detailed comment
 * 
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
public class CityActivity extends RequestActivity {
	private List<RetrieveInfoModel> groupArray;
	private List<List<RetrieveInfoModel>> childArray;
	private List<View> groupArrayView;
	private List<List<View>> childArrayView;

	public static List<RetrieveInfoModel> xuanzhongCity;// 选中城市
	public static List<RetrieveInfoModel> delCity;// 选中城市
	ImageView back;
	String result;

	TextView nextpage, titlename, text1;

	ExpandableListView expandable;
	ExpandableAdapter ea;

	RelativeLayout cidyname;

	LinearLayout selectcity;

	boolean buttonflag = true;

	String str;

	int type = 0;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		type = getIntent().getIntExtra("type", 0);// type=20单选

		xuanzhongCity = new ArrayList<RetrieveInfoModel>();
		delCity = new ArrayList<RetrieveInfoModel>();

		groupArray = new ArrayList<RetrieveInfoModel>();
		childArray = new ArrayList<List<RetrieveInfoModel>>();

		groupArrayView = new ArrayList<View>();
		childArrayView = new ArrayList<List<View>>();
		xuanzhongCity = new ArrayList<RetrieveInfoModel>();

		selectData_info(groupArray, "t_areas", "area_type=1");
		for (int i = 0; i < groupArray.size(); i++) {
			selectData_info(childArray, "t_areas", "parent_id="
					+ groupArray.get(i).getId(), i);
		}
		initView();
		addCityLayer();

	}

	private void selectData_info(List<RetrieveInfoModel> listModel,
			String tabname, String selection) {

		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		while (cursor.moveToNext()) {
			RetrieveInfoModel rim = new RetrieveInfoModel();
			int id = cursor.getInt(cursor.getColumnIndex("area_id"));
			String name = cursor.getString(cursor.getColumnIndex("area_name"));
			int isselected = cursor.getInt(cursor.getColumnIndex("isselected"));

			rim.setId(id);
			rim.setName(name);
			if (type == 20 || type == 21 || type == 19 || type == 0) {
				rim.setIsselected(0);
			} else
				rim.setIsselected(isselected);

			System.out.println("city:" + name);
			listModel.add(rim);
		}
		cursor.close();
		db.close();
		dh.close();

	}

	private void selectData_info(List<List<RetrieveInfoModel>> listModel,
			String tabname, String selection, int i) {
		List<RetrieveInfoModel> list = new ArrayList<RetrieveInfoModel>();
		List<View> view_list = new ArrayList<View>();
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getReadableDatabase();
		Cursor cursor = db.query(tabname, null, selection, null, null, null,
				null);
		boolean flag = true;
		while (cursor.moveToNext()) {
			RetrieveInfoModel rim = new RetrieveInfoModel();
			int id = cursor.getInt(cursor.getColumnIndex("area_id"));
			String name = cursor.getString(cursor.getColumnIndex("area_name"));
			int isselected = cursor.getInt(cursor.getColumnIndex("isselected"));

			rim.setId(id);
			rim.setName(name);
			if (type == 0 || type == 20 || type == 21 || type == 6
					|| type == 19) {
				rim.setIsselected(0);
			} else
				rim.setIsselected(isselected);

			if (rim.getIsselected() == 0) {
				flag = false;
			}

			if (rim.getIsselected() == 1) {
				xuanzhongCity.add(rim);
			}
			list.add(rim);
			// TextView textview = new TextView(this);
			// view_list.add(textview);
		}
		if (type <= 1) {
			RetrieveInfoModel rim = new RetrieveInfoModel();
			rim.setId(-1);
			rim.setName("全选");
			if (flag) {
				rim.setIsselected(1);
			} else
				rim.setIsselected(0);
			list.add(rim);
			// TextView textview = new TextView(this);
			// view_list.add(textview);
			childArrayView.add(view_list);
		}
		listModel.add(list);
		cursor.close();
		db.close();
		dh.close();

	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		super.onDestroy();
	}

	private void initView() {
		result = getIntent().getStringExtra("result");
		back = (ImageView) this.findViewById(R.id.back);
		back.setOnClickListener(this);
		nextpage = (TextView) this.findViewById(R.id.nextpage);
		titlename = (TextView) this.findViewById(R.id.titlename);
		text1 = (TextView) this.findViewById(R.id.text1);

		switch (type) {
		case 19:
			titlename.setText("项目所在地");
			text1.setText("项目地?");
			break;
		case 20:
			titlename.setText("项目所在地");
			text1.setText("项目地?");
			break;
		case 21:
			titlename.setText("家所在地");
			text1.setText("家所在地?");
			break;
		default:
			break;
		}

		cidyname = (RelativeLayout) this.findViewById(R.id.cidyname);
		cidyname.setOnClickListener(this);
		selectcity = (LinearLayout) this.findViewById(R.id.selectcity);

		nextpage.setOnClickListener(this);

		expandable = (ExpandableListView) this
				.findViewById(R.id.expandableListView);
		expandable.setGroupIndicator(null);
		ea = new ExpandableAdapter(this);
		expandable.setAdapter(ea);

		if (type == 0 || type == 6 || type == 20 || type == 21) {
			nextpage.setText("保存");
		}

	}

	@Override
	public Request getInitialRequest() {
		return null;

	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {

		if (bundle.containsKey(WooRequestFactory.BUNDLE_PREFERENCES_RESULT)) {

			System.out.println("偏好上传成功回调!");

			int result = bundle.getInt("result");

			if (result == 1) {
				Utils.messageInfo.isPreferences = 1;

				buttonflag = true;
				Gson datagson = new Gson();
				RetrieveInfoBean rib = datagson.fromJson(str,
						RetrieveInfoBean.class);

				String[] str = rib.projectCycle.split(",");
				// 109周期108行业126模块127岗位//10924性质
				ContentValues contentValues = new ContentValues();
				contentValues.put("isselected", 1);

				ContentValues Values = new ContentValues();
				Values.put("isselected", 0);
				charu("t_dictionary", Values,
						"pid=126 or pid=127 or pid=109 or pid=108");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}
				str = rib.projectIndustry.split(",");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}
				str = rib.projectAddress.split(",");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}
				str = rib.model.split(",");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}
				str = rib.station.split(",");
				for (int i = 0; i < str.length; i++) {
					charu("t_dictionary", contentValues, "id=" + str[i]);
				}

				str = rib.projectAddress.split(",");
				charu("t_areas", Values, "");
				for (int i = 0; i < str.length; i++) {
					charu("t_areas", contentValues, "area_id=" + str[i]);
				}
				Intent intent = new Intent();
				intent.putExtra("str", str);
				setResult(1, intent);
				finish();
			}

		}
	}

	public void charu(String tabname, ContentValues contentValues,
			String whereClause) {
		DatabaseHelper dh = new DatabaseHelper(this);
		SQLiteDatabase db = dh.getWritableDatabase();

		db.update(tabname, contentValues, whereClause, null);

		db.close();
		dh.close();
	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.cityactivity;

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = null;
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.nextpage:
			if (type == 19) {// 家所在地
				if (xuanzhongCity.size() > 0) {
					launchRequest(WooRequestFactory.updatePersonal(
							"homeAddress", xuanzhongCity.get(0).getId() + ""));
					intent = new Intent();
					intent.putExtra("id", xuanzhongCity.get(0).getId());
					intent.putExtra("name", xuanzhongCity.get(0).getName());
					setResult(20, intent);
					finish();
				} else {
					Toast.makeText(this, "必须选择一个城市！", Toast.LENGTH_LONG).show();
				}

			} else if (type == 20) {// 项目所在地
				if (xuanzhongCity.size() > 0) {
					launchRequest(WooRequestFactory
							.updatePersonal("projectAddress", xuanzhongCity
									.get(0).getId() + ""));
					intent = new Intent();
					intent.putExtra("id", xuanzhongCity.get(0).getId());
					intent.putExtra("name", xuanzhongCity.get(0).getName());
					setResult(20, intent);
					finish();
				} else {
					Toast.makeText(this, "必须选择一个城市！", Toast.LENGTH_LONG).show();
				}

			} else if (type == 21) {// 家所在地
				if (xuanzhongCity.size() > 0) {
					launchRequest(WooRequestFactory.updatePersonal(
							"homeAddress", xuanzhongCity.get(0).getId() + ""));
					intent = new Intent();
					intent.putExtra("id", xuanzhongCity.get(0).getId());
					intent.putExtra("name", xuanzhongCity.get(0).getName());
					setResult(21, intent);
					finish();
				} else {
					Toast.makeText(this, "必须选择一个城市！", Toast.LENGTH_LONG).show();
				}

			} else if (type == 0) {
				intent = new Intent();
				if (xuanzhongCity.size() > 0) {
					intent.putExtra("name", xuanzhongCity.get(0).getName());
					if (xuanzhongCity.size() > 1) {
						int size = xuanzhongCity.size();
						for (int i = 0; i < xuanzhongCity.size(); i++) {
							if (xuanzhongCity.get(i).getId() == -1) {
								--size;
							}
						}
						intent.putExtra("num", "等" + size + "个");
					} else
						intent.putExtra("num", "");
					intent.putExtra("result", resutData(intent, xuanzhongCity));
				} else {
					intent.putExtra("name", "全部");
					intent.putExtra("num", "");
					intent.putExtra("result", "");
				}
				setResult(6, intent);
				finish();
			} else {

				if (xuanzhongCity.size() == 0) {
					Toast.makeText(this, "必须选择一个城市！", Toast.LENGTH_LONG).show();
					return;
				}
				String citystr = "\"projectAddress\":\"";
				for (int i = 0; i < xuanzhongCity.size(); i++) {
					// System.out.println("-----" +
					// xuanzhongProject.get(i).getName());
					String douhao = ",";
					if (i == xuanzhongCity.size() - 1) {
						douhao = "\"}";
					}
					citystr = citystr + xuanzhongCity.get(i).getId() + douhao;
				}
				str = result + citystr;
				System.out.println("str:" + str);
				if (buttonflag) {
					buttonflag = false;
					launchRequest(WooRequestFactory.getPreferencesRequest(str));
				}
			}
			break;
		case R.id.cidyname:
			intent = new Intent(this, CityDialogActivity.class);
			startActivityForResult(intent, 0);
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (type == 0) {
				Intent intent = new Intent();
				intent.putExtra("name", "全部");
				intent.putExtra("num", "");
				intent.putExtra("result", "");
				setResult(6, intent);
				finish();
			} else {
				finish();
			}
			return true;

		}

		return super.onKeyDown(keyCode, event);

	}

	public String resutData(Intent intent, List<RetrieveInfoModel> list) {
		String str = list.get(0).getId() + "";
		for (int i = 1; i < list.size(); i++) {
			str += "," + list.get(i).getId();
		}

		return str;
	}

	public class ExpandableAdapter extends BaseExpandableListAdapter {
		Activity activity;

		public ExpandableAdapter(Activity a) {
			activity = a;
		}

		public Object getChild(int groupPosition, int childPosition) {
			return childArray.get(groupPosition);
		}

		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		public int getChildrenCount(int groupPosition) {
			return 1;
		}

		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			// String string = childArray.get(groupPosition);

			LayoutInflater mInflater = LayoutInflater.from(CityActivity.this);
			View view = mInflater.inflate(R.layout.cityviewitem, null);
			LinearLayout linear = (LinearLayout) view.findViewById(R.id.linear);
			if (childArrayView.size() == 0) {
				addView(linear,
						(List<RetrieveInfoModel>) getChild(groupPosition,
								childPosition), null);
			} else {
				addView(linear,
						(List<RetrieveInfoModel>) getChild(groupPosition,
								childPosition),
						childArrayView.get(groupPosition));
			}
			return view;
		}

		// group method stub
		public Object getGroup(int groupPosition) {
			return groupArray.get(groupPosition);
		}

		public int getGroupCount() {
			return groupArray.size();
		}

		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			LayoutInflater mInflater = LayoutInflater.from(CityActivity.this);
			View view = mInflater.inflate(R.layout.provincesviewitem, null);

			TextView provincestext = (TextView) view
					.findViewById(R.id.provincestext);
			provincestext.setText(((RetrieveInfoModel) getGroup(groupPosition))
					.getName());
			ImageView parentImageViw = (ImageView) view
					.findViewById(R.id.parentImageViw);

			if (isExpanded) {
				parentImageViw.setBackgroundResource(R.drawable.jiantoushang);
			} else {
				parentImageViw.setBackgroundResource(R.drawable.jiantouxia);
			}

			return view;
		}

		private void addView(LinearLayout layer,
				final List<RetrieveInfoModel> listrim,
				final List<View> list_view) {
			List<View> listtextview = new ArrayList<View>();

			for (int i = 0; i < listrim.size(); i++) {
				LayoutInflater mInflater = LayoutInflater
						.from(CityActivity.this);
				View view = mInflater.inflate(R.layout.textviewitem, null);
				String text = listrim.get(i).getName();
				TextView textview = (TextView) view.findViewById(R.id.textview);
				if (list_view != null)
					list_view.add(i, textview);
				textview.setBackgroundResource(R.drawable.weixuanzhong);
				textview.setText(text);
				textview.setTag(listrim.get(i));
				if (i == listrim.size() - 1 && type <= 19) {
					boolean flag = true;
					for (int j = 1; j < listrim.size() - 1; j++) {
						if (listrim.get(0).getIsselected() != listrim.get(i)
								.getIsselected()) {
							flag = false;
						}
					}

					if (flag) {
						if (listrim.get(0).getIsselected() == 1) {
							listrim.get(listrim.size() - 1).setIsselected(1);
						} else {
							listrim.get(listrim.size() - 1).setIsselected(0);
						}
					} else {
						listrim.get(listrim.size() - 1).setIsselected(0);
					}
				}

				if (listrim.get(i).getIsselected() == 0) {
					textview.setTextColor(Color.rgb(66, 66, 66));
					textview.setBackgroundResource(R.drawable.weixuanzhong);
				} else {
					textview.setTextColor(Color.rgb(255, 255, 255));
					textview.setBackgroundResource(R.drawable.xuanzhong);
				}

				textview.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						TextView tv = (TextView) v;
						RetrieveInfoModel rm = (RetrieveInfoModel) tv.getTag();
						// if ((type == 21 && xuanzhongCity.size() == 1)
						// || (type == 20 && xuanzhongCity.size() == 1)
						// || (type == 19 && xuanzhongCity.size() == 1)) {
						// Toast.makeText(CityActivity.this, "只能选择1个城市!",
						// Toast.LENGTH_LONG).show();
						// return;
						// }

						if (rm.getIsselected() == 0) {
							if (rm.getId() != -1) {
								boolean flag = true;
								// rm.setIsselected(1);
								// tv.setTextColor(Color.rgb(255, 255, 255));
								// tv.setBackgroundResource(R.drawable.xuanzhong);

								if (!xuanzhongCity.contains(rm)) {
									if (xuanzhongCity.size() > 0 && type >= 19) {
										for (int i = 0; i < childArray.size(); i++) {
											for (int j = 0; j < childArray.get(
													i).size(); j++) {
												// if (childArray.get(i).get(j)
												// .getId() != rm.getId()
												// && childArray
												// .get(i)
												// .get(j)
												// .getIsselected() == 1) {
												childArray.get(i).get(j)
														.setIsselected(0);
												// }
											}
										}

										xuanzhongCity = new ArrayList<RetrieveInfoModel>();
									}
									rm.setIsselected(1);
									tv.setTextColor(Color.rgb(255, 255, 255));
									tv.setBackgroundResource(R.drawable.xuanzhong);
									xuanzhongCity.add(rm);
									ea.notifyDataSetChanged();
								}

								if (type <= 1) {
									for (int k = 0; k < listrim.size() - 1; k++) {
										if (listrim.get(k).getIsselected() == 0) {
											flag = false;
											break;
										}
									}
									if (flag) {
										listrim.get(listrim.size() - 1)
												.setIsselected(1);
										((TextView) list_view.get(listrim
												.size() - 1))
												.setTextColor(Color.rgb(255,
														255, 255));
										((TextView) list_view.get(listrim
												.size() - 1))
												.setBackgroundResource(R.drawable.xuanzhong);
									}
								}
							} else {
								for (int k = 0; k < listrim.size(); k++) {
									listrim.get(k).setIsselected(1);
									((TextView) list_view.get(k))
											.setTextColor(Color.rgb(255, 255,
													255));
									((TextView) list_view.get(k))
											.setBackgroundResource(R.drawable.xuanzhong);

									if (!xuanzhongCity.contains(listrim.get(k))) {
										xuanzhongCity.add(listrim.get(k));
									}
								}
							}
							addCityLayer();
						} else {
							if (rm.getId() != -1) {
								boolean flag = true;
								rm.setIsselected(0);
								tv.setTextColor(Color.rgb(66, 66, 66));
								tv.setBackgroundResource(R.drawable.weixuanzhong);
								if (xuanzhongCity.contains(rm)) {
									xuanzhongCity.remove(rm);
								}
								if (type <= 1) {
									for (int k = 0; k < listrim.size(); k++) {
										if (listrim.get(k).getIsselected() == 0) {
											flag = false;
											break;
										}
									}
									if (!flag) {
										listrim.get(listrim.size() - 1)
												.setIsselected(0);
										((TextView) list_view.get(listrim
												.size() - 1))
												.setTextColor(Color.rgb(66, 66,
														66));
										((TextView) list_view.get(listrim
												.size() - 1))
												.setBackgroundResource(R.drawable.weixuanzhong);
									}
								}
							} else {
								for (int k = 0; k < listrim.size(); k++) {
									listrim.get(k).setIsselected(0);
									((TextView) list_view.get(k))
											.setTextColor(Color.rgb(66, 66, 66));
									((TextView) list_view.get(k))
											.setBackgroundResource(R.drawable.weixuanzhong);

									if (xuanzhongCity.contains(listrim.get(k))) {
										xuanzhongCity.remove(listrim.get(k));
									}
								}
							}
							addCityLayer();
						}

					}
				});

				Paint paint = new Paint();
				paint.setTextSize(textview.getTextSize());
				float size = paint.measureText(textview.getText().toString());
				view.setTag((int) size
						+ Utils.dip2px(CityActivity.this, 10 * 2 + 10));

				listtextview.add(view);
			}
			int j = 0;
			LinearLayout llayout = null;
			int MaxWidth = MainActivity.widthPixels
					- Utils.dip2px(CityActivity.this, 20);
			int temporarywidth = 0;
			while (true) {
				View view = null;
				int tagwidth = 0;
				if (j == listtextview.size()) {
					return;
				} else {
					view = listtextview.get(j);

					tagwidth = (Integer) view.getTag();
				}
				if (j == 0) {
					llayout = new LinearLayout(CityActivity.this);
				}
				System.out.println("textview:" + tagwidth + "temporarywidth:"
						+ temporarywidth + "MaxWidth:" + MaxWidth);
				if (tagwidth + temporarywidth < MaxWidth) {
					temporarywidth += tagwidth;
					llayout.addView(view);
				} else {
					layer.addView(llayout);

					LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.MATCH_PARENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					layoutParams.setMargins(0, 15, 0, 0);

					llayout = new LinearLayout(CityActivity.this);
					llayout.setLayoutParams(layoutParams);
					temporarywidth = (Integer) view.getTag();

					llayout.addView(view);
				}

				if (j == listtextview.size() - 1) {
					layer.addView(llayout);
				}
				j++;
			}
		}

		public boolean hasStableIds() {
			return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}

	void addCityLayer() {
		selectcity.removeAllViews();
		if (xuanzhongCity.size() == 0) {
			return;
		}
		for (int i = xuanzhongCity.size() - 1; i >= 0; i--) {
			if (xuanzhongCity.get(i).getId() == -1)
				continue;
			LayoutInflater mInflater = LayoutInflater.from(CityActivity.this);
			View view = mInflater.inflate(R.layout.textviewitem, null);
			String text = xuanzhongCity.get(i).getName();

			System.out.println("text:" + text);
			TextView textview = (TextView) view.findViewById(R.id.textview);
			textview.setBackgroundResource(R.drawable.weixuanzhong);
			textview.setText(text);

			selectcity.addView(view);
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) { // resultCode为回传的标记，我在B中回传的是RESULT_OK
		case 1:
			if (delCity.size() > 0) {
				for (int i = 0; i < childArray.size(); i++) {
					List<RetrieveInfoModel> rm = childArray.get(i);
					for (int j = 0; j < rm.size(); j++) {
						RetrieveInfoModel rim = rm.get(j);
						for (int k = 0; k < delCity.size(); k++) {
							if (rim.getId() == delCity.get(k).getId()) {
								rim.setIsselected(0);
							}
						}
					}
				}
				delCity = new ArrayList<RetrieveInfoModel>();
				addCityLayer();
				ea.notifyDataSetChanged();
			}
			break;
		default:

			break;
		}
	}
}
